package cn.tyoui.analyzerImpl;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * 分析+扩展集合类
 *
 * @author Tyoui
 * @version 1.8.1
 */
public class Bomap implements Runnable {
    static Logger log = Logger.getLogger(Bomap.class);
    private Analysis analysis;
    private int port = 12345;

    public Bomap(int port) {
        this.port = port;
        if (analysis == null)
            analysis = new Analysis();
    }

    /**
     * 启动服务
     *
     * @param serverSocket 开启服务
     */
    public void server(ServerSocket serverSocket) {
        try {
            Socket socket = serverSocket.accept();
            String url = analysis.socket(socket);//获取数据
            if (url.contains("favicon.ico"))
                return;
            url = analysis.decode(url);//编码数据
            Map<String, String> map = analysis.keyWord(url);//提取数据
            if (map.get("url") != null) {//判断数据
                List<String> list = analysis.participle(map.get("url"), true);//分析数据
                String text = analysis.listToString(list, ",");//转换数据成JSON
                log.info("分析的数据-->" + text);
                analysis.sendMessageURL(socket, analysis.json(text, ","));//显示数据
            }
            Thread.sleep(500);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    @Override
    public void run() {
        boolean flag = true;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            log.info(e.getMessage());
            flag = true;
        }
        while (flag) {
            server(serverSocket);
        }
    }
}

